/**
 * Created by suweiming on 2018/2/7.
 */
function checkPlugin(plugin) {
    if (!plugin) {
        throw new Error('' + plugin + ' not defined or not include!');
        return;
    }
}






/**
 *  日期插件
 */
function fnDate(obj) {
    checkPlugin(laydate);
    laydate.render({
        elem: '#' + obj.eleId //指定元素
    })
}
/**
 *
 * 多行溢出
 * @param ele 元素
 * @param num 行数
 */
function fnClamp(ele, num) {
    checkPlugin($clamp);
    if (ele instanceof Array) {
        ele.map(function (item) {
            $clamp(item, {clamp: num || 1})
        })
    } else {
        $clamp(ele, {clamp: num || 1})
    }
}

/**
 * 城市选择初始化
 * @param obj
 * @returns {{cnter: (*|jQuery|HTMLElement), $city: (*|jQuery|HTMLElement)}}
 */
function fnCity(obj) {
    obj = obj || {};
    var $city = $('#' + $('[name=city]').attr('id'));
    var $cityCtner = $('<div>');
    $cityCtner.css({
        marginBottom: '35px',
        position: 'relative',
    });
    $cityCtner.insertBefore($city);
    $city.appendTo($cityCtner);
    $city.citypicker({
        level: obj.level || 'province + city',
        city: obj.city || '',
        province: obj.province || '',
        district: obj.district || '',
    });
    return {
        cnter: $cityCtner,
        $city: $city,

    }
}
/**
 * spark line  fn
 * @param obj
 */
function fnSparkLine(obj) {
    $(obj.ele).sparkline(obj.values, {type: obj.type || 'bar', barColor: obj.color || 'green'});

}

var FETCH_CACHE = {};

/**
 * 获取数据，如果已经获取，下次进入时从内存中读取
 * @param url
 * @param DATA_
 * @returns {*}
 */
function getDataByUrl(url, DATA_) {

    var dtd = $.Deferred();
    if (!FETCH_CACHE[DATA_]) { // undefined
        FETCH_CACHE[DATA_] = {DATA: '', STATUS: false};
    }
    if (!!FETCH_CACHE[DATA_].DATA) { // 直接返回当前数据
        dtd.resolve(FETCH_CACHE[DATA_].DATA);
    } else {
        if (!FETCH_CACHE[DATA_].STATUS) {
            FETCH_CACHE[DATA_].STATUS = true;
            $.get(url, function (data) {
                if (data.code == 200) {
                    FETCH_CACHE[DATA_].DATA = data.list;
                    dtd.resolve(FETCH_CACHE[DATA_].DATA);
                } else {
                    dtd.reject(data.error)
                }
                FETCH_CACHE[DATA_].STATUS = false;
            });
        } else {
            //暂行解决方法
            var inter = setInterval(function () {
                if (!!FETCH_CACHE[DATA_].STATUS) {
                    dtd.resolve(FETCH_CACHE[DATA_].DATA);
                    clearInterval(inter);
                }
            }, 100);
        }
    }
    return dtd.promise();
}

/**
 * 下拉选择框 opt.name ：dom元素名称, opt.change:所选值变更事件
 */
function initSelect(opt) {
    var $g = $('[name=' + opt.name + ']');
    //
    if ($g.length) {
        if ($g.data('init'))return; // 防止重复初始化
        if (opt.data) { // 提供数据
            initS(opt.data);
        } else { // 服务点请求数据
            $.when(parent.window.getDataByUrl(opt.url, "S" + genId()))
                .then(function (list) {
                    initS(list.list || list);
                });
        }
    }
    function initS(list) {
        var $goodsId = $('<select name="' + opt.name + '"></select>');
        $('[name=' + opt.name + ']').replaceWith($goodsId);
        $goodsId.append('<option value="">全部' + (opt.label || '') + '</option>')
        list.map(function (item) {
            $goodsId.append('<option value="' + item.id + '">' + item.name + '</option>')
        });
        $goodsId.selectpicker({
            liveSearch: true,
        });
        $goodsId.data('init', $goodsId);
        $goodsId.closest('.bootstrap-select').css('width', 'auto');
        $goodsId.on('changed.bs.select', function (e) {
            var $t = $(e.target);
            opt.change && opt.change($t.val(), $t)
        });
        if (opt.selected) {
            $goodsId.selectpicker('val', opt.selected);
        }
    }
}

//错误处理
window.onerror = function (errorMessage, scriptURI, lineNumber, columnNumber, errorObj) {
    console.log("------------错误信息：", errorMessage);
    console.log("------------出错文件：", scriptURI.substring(scriptURI.lastIndexOf('www')));
    console.log("------------出错行号：", lineNumber);
    console.log("------------出错列号：", columnNumber);
    console.log("------------错误详情：", errorObj);
}